<?php
   
function xml2posts($xml) {
    global $posts, $currentPost, $key;
    $posts = array();
    $currentPost = null;
    $key = null;
    
    function saxStartElement($parser, $name, $attrib) {
        global $currentPost, $key;
        switch ($name) {
            case 'post':
                $currentPost = array('id' => $attrib['id']);
                break;
            case 'user':
                 if($currentPost != null) {
                     $key = 'user';
                 }
                break;
            case 'date':
                $key = 'date';
                break;
            case 'message':
                $key = 'message';
                break;
            default:
                $key = null;
                break;
        }
    }

    function saxEndElement($parser, $name) {
        global $posts, $currentPost, $key;
        if($name == 'post' && is_array($currentPost)) {
            $posts[] = $currentPost;
            $currentPost = null;
        }
        $key = null;
    }

    function saxCharacterData($parser, $data) {
        global $currentPost, $key;
        if($key != null && is_array($currentPost)) {
            $currentPost[$key] = $data;
        }
    }

    $parser = xml_parser_create();

    xml_set_element_handler($parser, 'saxStartElement', 'saxEndElement');
    xml_set_character_data_handler($parser, 'saxCharacterData');

    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);

    if(!xml_parse($parser, $xml, true)) {
        print_r($posts);
        die(sprintf("Ошибка XML: %s в строке %d\n",
            xml_error_string(xml_get_error_code($parser)),
            xml_get_current_line_number($parser)));
	}

	xml_parser_free($parser);

    return $posts;
}
